const Router = require('koa-router')
const { HttpException, ParameterException, NotFound } = require('../../core/http-exception')
const { SuccessResult } = require('../lib/helper')
const { PositiveIntegerValidator } = require('../validators/paramvalidateDemo')
const { ProductQueryValidator, TopNumValidator } = require('../validators/productQueryValidator')
const CompanyInfo = require('../models/CompanyInfo')
const Focus = require('../models/Focus')
const Partner = require('../models/Partner')
const SitePage = require('../models/SitePage')
const ProCate = require('../models/ProCate')
const Product = require('../models/Product')

const router = new Router()

router.get('/', async(ctx, next) => {  
  ctx.body = `<h1>Hello,这里是我做企业站api</h1>`
})

router.get('/error/:id', async(ctx, next) => { // 该路由只是做测试用
  const v = await new PositiveIntegerValidator().validate(ctx)
  const id = v.get('path.id')
  ctx.body = {
    id: id
  }
})

/**
 * 获取企业的基本信息
 */
router.get('/siteinfo', async(ctx) => {
  const compInfo = await CompanyInfo.findOne()
  if(!compInfo) throw new NotFound()
  if(compInfo.QRCode && !compInfo.QRCode.startsWith('http')) {
    compInfo.QRCode = ctx.origin + compInfo.QRCode
  }
  ctx.body = new SuccessResult(compInfo)
})

/**
 * 获取轮播图列表
*/
router.get('/focus', async(ctx) => {
  const httpOrigin = ctx.origin
  const focus = await Focus.findAll({ attributes: { exclude: ['createdAt','updatedAt'] } })
  focus.forEach(item => item.imgSrc = httpOrigin + item.imgSrc ) // 给图片加上 http://localhost:8888前缀
  ctx.body = new SuccessResult(focus)
})

/**
 * 获取合作伙伴
*/
router.get('/partner', async(ctx) => {
  const httpOrigin = ctx.origin
  const partner = await Partner.findAll({ attributes: { exclude: ['createdAt','updatedAt'] } })
  partner.forEach(item => item.imgSrc = httpOrigin + item.imgSrc ) // 给图片加上 http://localhost:8888前缀
  ctx.body = new SuccessResult(partner)
})

/**
 * 获取合作伙伴
*/
router.get('/honor', async(ctx) => {
  const sitePage = await SitePage.findOne({ where: { title: '企业荣誉'} ,attributes: { exclude: ['createdAt','updatedAt'] } })
  ctx.body = new SuccessResult(sitePage)
})

/**
 * 获取产品分类
*/
router.get('/procate', async(ctx) => {
  const allCates = await ProCate.findAll({ attributes: { exclude: ['createdAt','updatedAt'] } })
  ctx.body = new SuccessResult(allCates)
})

/**
 * 获取产品分页数据
*/
router.post('/pageproduct/:id?', async(ctx) => {
  const v = await new ProductQueryValidator().validate(ctx)
  const pageIndex = v.get('body.pageIndex')
  const pageSize = v.get('body.pageSize')

  const cateId = v.get('path.id')
  let where = null
  if(cateId) { // 如果有传入分类id, 表明是查询该分类下的分页数据，默认是所有产品的分页数据
    where = {
      ProCateId: cateId * 1
    }
  }

  const offset = (pageIndex - 1) * pageSize

  const products = await Product.findAndCountAll({
    where: where, 
    attributes: { exclude: ['createdAt','updatedAt'] },
    include: [
      { model: ProCate, required: true, attributes: { exclude: ['content','createdAt','updatedAt'] } }
    ],
    order: [
      ['orderNum', 'DESC']
    ],
    offset: offset,
    limit: pageSize
  })
  const httpOrigin = ctx.origin
  products.rows.forEach(item => item.pic = httpOrigin + item.pic)
  ctx.body = new SuccessResult(products)
})

/**
 * 取首页的推荐产品 （滚动轮播的产品）
 */
router.get('/topproduct/:top', async(ctx) => {
  const v = await new TopNumValidator().validate(ctx)
  const top = v.get('path.top')
  const products = await Product.findAll({
    where: {
      isRecommend: 1
    },
    attributes: { exclude: ['content','createdAt','updatedAt'] },
    order: [
      ['orderNum', 'DESC']
    ],
    limit: top
  })
  const httpOrigin = ctx.origin
  products.forEach(item => item.pic = httpOrigin + item.pic)
  ctx.body = new SuccessResult(products)
})

/*
  获取产品详情
*/
router.get('/productdetail/:id', async(ctx) => {
  const v = await new PositiveIntegerValidator().validate(ctx)
  const id = v.get('path.id')

  const product = await Product.findOne({
    where: { id },
    attributes: { exclude: ['createdAt','updatedAt'] },
  })
  if(!product) throw new NotFound()
  const httpOrigin = ctx.origin
  product.pic = product.pic? httpOrigin + product.pic : ''
  ctx.body = new SuccessResult(product)
})

// module.exports = { router } // 这种导出路由的方式也支持
module.exports = router